# coding=utf-8
"""
Author: Mr.夏末
@Function: Web自动化关键字封装
"""
<<<<<<< HEAD
import time,re
=======
import time
import re
>>>>>>> bbe5575b39a883d3ba625b099ff1bdaa9564f25f

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.select import Select
from class10.verify import Verify
from class11.desc import relations
<<<<<<< HEAD
from common.Logger import logger,path
=======
>>>>>>> bbe5575b39a883d3ba625b099ff1bdaa9564f25f


class Web:
    """web自动化关键字类"""

    def __init__(self):
        self.driver: webdriver.Chrome = None
        #使用字典保存关联的数据
        self.relation_dict = {}

    def openbrowser(self, br='gc'):
        """
        打开浏览器
        :param br: 默认是谷歌浏览器，支持IE、Firefox、Edge
        :return:
        """
        if br == 'ff':
            self.driver = webdriver.Firefox()
        elif br == 'edge':
            self.driver = webdriver.Edge()
        else:
            # 使用options，去掉自动化软件控制的标识
            option = Options()
            option.add_experimental_option('excludeSwitches', ['enable-automation'])
            option.add_argument('--disable-blink-features=AutomationControlled')
            ##关掉密码弹窗
            prefs = {}
            prefs['credentials_enable_service'] = False
            prefs['profile.password_manager_enabled'] = False
            option.add_experimental_option('prefs', prefs)

            self.driver = webdriver.Chrome(options=option)
        # 默认配置隐式等待
        self.driver.implicitly_wait(10)
        self.driver.maximize_window()

    def get_url(self, url=''):
        """
        打开网站
        :param url: 网站地址
        :return:
        """
        if url.startswith('http'):
            self.driver.get(url)
        else:
            self.driver.get('http://' + url)

    def __find_ele(self,locator=''):
        if locator.startswith('/') or locator.startswith('('):
            ele = self.driver.find_element('xpath',locator)
        elif locator.startswith('#'):
            ele = self.driver.find_element('css selector',locator)
        else:
            ele = self.driver.find_element('id',locator)
<<<<<<< HEAD
        #给操作的元素高亮显示
        if ele:
            self.driver.execute_script('arguments[0].style.background = "#00ff50"',ele)
=======
>>>>>>> bbe5575b39a883d3ba625b099ff1bdaa9564f25f
        return ele

    @relations
    def input(self,locator='',value=''):
        """输入
        :param locator: 定位器 xpath、CSS、ID、ClassName
        :param value: 输入的值
        """
        ele = self.__find_ele(locator)
<<<<<<< HEAD
        if value.endswith('.jpg') or value.endswith('.png'):
            value = path + 'lib\\' + value
        ele.send_keys(value)

    def clear(self,locator):
        """清空输入框"""
        ele = self.__find_ele(locator)
        ele.clear()

=======
        ele.send_keys(value)

>>>>>>> bbe5575b39a883d3ba625b099ff1bdaa9564f25f
    def click(self,locator):
        """点击"""
        ele = self.__find_ele(locator)
        ele.click()

    def clicktry(self,locator):
        """点击"""
        try:
            time.sleep(2)
            ele = self.__find_ele(locator)
            ele.click()
        except Exception as e:
            print('尝试点击元素%s错误' % locator)
        finally:
            time.sleep(1)

    def slide12306(self):
        # 找到滑块
        ele1 = self.__find_ele('//span[@id="nc_1_n1z"]')
        ele2 = self.__find_ele('//span[@class="nc-lang-cnt"]')
        # 使用action滑动
        action = ActionChains(self.driver)
        # 按住滑块
        action.click_and_hold(ele1)
        # 拖到最右边
        action.move_by_offset(ele2.size.get('width'), 0)
        # 松开鼠标
        action.release()
        # 让这些动作执行
        action.perform()

<<<<<<< HEAD
    def get_verify(self,locator):
        # 截取验证码图片
        vimg = self.__find_ele(locator)
        vimg.screenshot(path + 'class11\\verify.png')
=======
    def get_verify(self):
        # 截取验证码图片
        vimg = self.__find_ele('//*[@id="verify_code_img"]')
        vimg.screenshot('./verify.png')
>>>>>>> bbe5575b39a883d3ba625b099ff1bdaa9564f25f
        # 获取验证码
        verify = Verify('wuqingfqng', 'wuqing&fqng', '904357')
        # verify = Verify('17863087593','hzs123456','937288')
        # 调用方法，获取验证码
<<<<<<< HEAD
        ver = verify.get_verify(path + 'class11\\verify.png')
=======
        ver = verify.get_verify('./verify.png')
>>>>>>> bbe5575b39a883d3ba625b099ff1bdaa9564f25f
        self.relation_dict['verify'] = ver
        return ver

    def jsclick(self,locator):
        """js点击"""
        ele = self.__find_ele(locator)
        self.driver.execute_script('return arguments[0].className',ele)

    def get_text(self,locator,reg=''):
        """
        获取元素文本
        :param locator:
        :param reg:对文本进行正则处理
        """
        ele = self.__find_ele(locator)
        text =  ele.text
        # 如果有正则，按照正则处理
        if reg:
            text = re.findall(reg,text)
            if text:
                text = text[0]
        # 获取到属性可以变成一个系统变量，{text}保存起来
        self.relation_dict['text'] = text
        return text

<<<<<<< HEAD
    def gettitle(self):
        """获取标题"""
        title = self.driver.title
        self.relation_dict['title'] = title
        return title


=======
>>>>>>> bbe5575b39a883d3ba625b099ff1bdaa9564f25f
    @relations
    def saveparams(self,param_name='',value=''):
        """
        把参数保存为特定名字
        :param param_name: 参数名
        :param value: 参数值
        """
        self.relation_dict[param_name] = value

    def sleep(self,t='1'):
        try:
            t = float(t)
        except Exception as e:
            print(e.__str__())
            t = 1
        time.sleep(t)

    def select(self,locator='',value=''):
        # 找到select元素
        ele = self.__find_ele(locator)
        # 用select元素创建selenium的select对象
        select = Select(ele)
        try:
            # 整数使用value
            value = int(value)
            select.select_by_value(str(value))
        except:
            # 其他使用text
            select.select_by_visible_text(value)

    def assertno(self,value1='',value2=''):
        """
        断言不相等
        :param value1: 期望值
        :param value2: 实际值
        """
        if value1 == value2:
            print('断言失败')
<<<<<<< HEAD
            return False,f"断言失败，实际结果{value2}"
=======
            return False
>>>>>>> bbe5575b39a883d3ba625b099ff1bdaa9564f25f
        else:
            print('断言成功')
            return True

    def switchwin(self,title=''):
        # 切换窗口
        # 获取窗口的标志id列表
        handles = self.driver.window_handles
        print(handles)
        # 按下标
        try:
            title = int(title)
            self.driver.switch_to.window(title)
        except:
            # 标题切换
            for i in handles:
                self.driver.switch_to.window(i)
                if self.driver.title.__contains__(title):
                    break

    def Iframe(self,loicator=''):
        """进入iframe"""
        ele = self.__find_ele(loicator)
        self.driver.switch_to.frame(ele)

    def outiframe(self,loicator=''):
        """退出iframe"""
        self.driver.switch_to.default_content()